package com.ruoyi.common.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import com.ruoyi.config.Global;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

//import okhttp3.OkHttpClient;
//import okhttp3.Request;
//import okhttp3.ResponseBody;

public class QiNiuUtils {

    public static String uploadQiNiu(MultipartFile file) {
        String qiniuUrl = Global.getQiniuUrl() == null ? "http://q6lwcxvp6.bkt.clouddn.com" : Global.getQiniuUrl();
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = Global.getAccessKey() == null ? "JnzePtwoAiscVwOcxEgJJx7ELiL3xJxPd7Sj7Hhu" : Global.getAccessKey();
        String secretKey = Global.getSecretKey() == null ? "Db7gRImgHEA8-XIw7MQJVQ_3f7MfyQ81IgnfdATF" : Global.getSecretKey();
        String bucket = Global.getBucket() == null ? "book" : Global.getBucket();
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        try {
            byte[] uploadBytes = file.getBytes();
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(uploadBytes);
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(byteInputStream, key, upToken, null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                return qiniuUrl + "/" + putRet.key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 视频
     * @param file
     * @return
     */
    public static String uploadQiniuVideo(MultipartFile file) {

        String qiniuUrl = Global.getQiniuUrl() == null ? "http://q6lwcxvp6.bkt.clouddn.com" : Global.getQiniuUrl();
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = Global.getAccessKey() == null ? "JnzePtwoAiscVwOcxEgJJx7ELiL3xJxPd7Sj7Hhu" : Global.getAccessKey();
        String secretKey = Global.getSecretKey() == null ? "Db7gRImgHEA8-XIw7MQJVQ_3f7MfyQ81IgnfdATF" : Global.getSecretKey();
        String bucket = Global.getBucket() == null ? "book" : Global.getBucket();
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        try {
            String fileName = file.getOriginalFilename();
            key = fileName.substring(0,fileName.lastIndexOf("."));

            byte[] uploadBytes = file.getBytes();
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(uploadBytes);
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            key = key + ".mp4";
            try {
                Response response = uploadManager.put(byteInputStream, key, upToken, null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                return qiniuUrl + "/" + putRet.key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void deleteFile(String key){
        //...生成上传凭证，然后准备上传
        String accessKey = Global.getAccessKey() == null ? "o00yIbSXAf3m_hf3mDSZUfIlx7v9h4Ee81-9w_IO" : Global.getAccessKey();
        String secretKey = Global.getSecretKey() == null ? "4-yMtabgFVYPlJwle7WR_G1EQX9bNFhlsoXCRijQ" : Global.getSecretKey();
        Auth auth = Auth.create(accessKey, secretKey);
        Configuration config = new Configuration(Zone.autoZone());
        BucketManager bucketMgr = new BucketManager(auth, config);
        //指定需要删除的文件，和文件所在的存储空间
        String bucket = Global.getBucket() == null ? "hzp" : Global.getBucket();
       try {
            Response delete = bucketMgr.delete(bucket, key);
            delete.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("结束了");
    }

    /**
     * 下载文件
     */
//    public static File download(String url) {
//
//        OkHttpClient client = new OkHttpClient();
//        System.out.println(url);
//        Request req = new Request.Builder().url(url).build();
//        okhttp3.Response resp = null;
//        File imgFile = null;
//        try {
//            resp = client.newCall(req).execute();
//            System.out.println(resp.isSuccessful());
//            if (resp.isSuccessful()) {
//                ResponseBody body = resp.body();
//                InputStream is = body.byteStream();
//                byte[] data = readInputStream(is);
//                //判断文件夹是否存在，不存在则创建
//                //本地保存路径
//                String filePath = "C:\\profile\\info\\";
//                File file = new File(filePath);
//                if (!file.exists() && !file.isDirectory()) {
//                    file.mkdir();
//                }
//                String fileName = "1.jpg";
//                if(url != null) {
//                    fileName = url.substring(26);
//                }
//                imgFile = new File(filePath + fileName+".jpg");
//                FileOutputStream fops = new FileOutputStream(imgFile);
//                fops.write(data);
//                fops.close();
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//            System.out.println("Unexpected code " + resp);
//        }
//        return imgFile ;
//    }

    /**
     * 读取字节输入流内容
     *
     * @param is
     * @return
     */
    private static byte[] readInputStream(InputStream is) {
        ByteArrayOutputStream writer = new ByteArrayOutputStream();
        byte[] buff = new byte[1024 * 2];
        int len = 0;
        try {
            while ((len = is.read(buff)) != -1) {
                writer.write(buff, 0, len);
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return writer.toByteArray();
    }




}
